package com.lyx.shirotest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.env.BasicIniEnvironment;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;

/**
 * @author LiuYunXin
 * @create 2022-12-22-23:14
 */
public class ShiroRun {
    public static void main(String[] args) {
       /*
       1.初始化SecurityManager
       2.获取Subject对象
       3.创建token对象，web应用用户名密码从页面传递
       4.完成登录
       */
        //1. IniSecurityManagerFactory弃用->使用BasicIniEnvironment
        IniSecurityManagerFactory factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        // BasicIniEnvironment basicIniEnvironment = new BasicIniEnvironment("classpath:shiro.ini");
        SecurityManager securityManager = factory.getInstance();
        SecurityUtils.setSecurityManager(securityManager);
        //2
        Subject subject = SecurityUtils.getSubject();
        //3
        AuthenticationToken token = new UsernamePasswordToken("zhangsan","z3");
        //4
        try {
            subject.login(token);
            System.out.println("登录成功");
            //5判断角色
            boolean hasRole = subject.hasRole("role1");
            System.out.println("是否拥有此hasRole:"+hasRole);
            //6判断权限
            boolean permitted = subject.isPermitted("user:insert");
            System.out.println("是否拥有此权限:" + permitted);
            // 也可以使用check方法，没有返回值，没权限则抛出AuthenticationException
            // subject.checkPermission("user:insert");
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            System.out.println("用户不存在");
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            System.out.println("密码错误");
        } catch (AuthenticationException e) {
            e.printStackTrace();
        }
    }
}
